package com.oauth2.client.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.oauth2.client.util.HttpUtilslwl;

@Controller
public class IndexController {

	@RequestMapping(value = "/home")
	public String name() {
		return "home";
	}
	
	//像授权服务器发起授权请求
	@RequestMapping(value="/authorize")
	public String authorize() {
		String url = "redirect:http://localhost:8081/oauth2_provider/oauth/authorize?"
				+ "client_id=tonr-with-redirect&"
				+ "redirect_uri=http://localhost:8080/oauth2_client/callback&"
				+ "response_type=code&"
				+ "scope=read%20write&"
				+ "state=lwl";
		return url;
	}

	//授权服务器回调返回code
	@RequestMapping(path = "/callback")
	@ResponseBody
	public String callBack(String code) {
		System.out.println("code: " + code);
		
		return getToken(code);
	}
	
	//获取token
	private String getToken(String code) {
		String strUrl = "http://localhost:8081/oauth2_provider/oauth/token";
		// 设置请求参数,key为参数名,value为参数值
		Map<String, String> params = new HashMap<>();
		params.put("grant_type", "authorization_code");// 第一次获取Token固定请求参数
		params.put("client_id", "tonr-with-redirect");
		params.put("client_secret", "secret");
		params.put("code", code);
		params.put("redirect_uri", "http://localhost:8080/oauth2_client/callback");

		HttpUtilslwl httpUtils = new HttpUtilslwl();
		String respStr = httpUtils.httpClientdoGet(strUrl, params, null);
		
		
		return respStr;
	}
	
	
	

}
